
(function($) {
    var TEDebug = true;
    var _TEDebugger = function(msg){
        if(TEDebug){
            //console.log(msg);
        }
    }
    var TEColumn = function(){
        this.index = null;
        this.ele = null;
        this.dir = null;
        this.instance = null;
        this.setClass = function(){
            this.ele.removeClass('sorting_asc');
            this.ele.removeClass('sorting_desc');
            this.ele.removeClass('sorting');
            if(this.dir){
                if(this.dir === 'asc'){
                    this.ele.addClass('sorting_asc');
                }else if(this.dir === 'desc'){
                    this.ele.addClass('sorting_desc');
                }
            }else{
                this.ele.addClass('sorting');

            }
        }
        this.nextSort = function(){
            if(this.dir){
                if(this.dir === 'desc'){
                    this.dir = null;
                }else if(this.dir === 'asc'){
                    this.dir = 'desc';
                }
            }else{
                this.dir = 'asc';
            }
            _TEDebugger(this.ele.text() + ' sort dir: ' + this.dir);
            this.setClass();
        }
        this.load = function(index, element, instance){
            this.index = index;
            this.ele = $(element);
            this.instance = instance;
            for(var i in instance.options.sort){                
                var sort = instance.options.sort[i];
                if(sort[0] == this.index){
                    this.dir = sort[1];
                }
            }
            this.setClass();
            var t = this;
            this.ele.bind('click',  function(event){
                t.nextSort();
                t.instance.clickManager(event, this.index, this);
            });
            
        }
    };
    $.fn.tableExtender = function tableExtender(options){
        this.defaults = {
            "id": $(this),
            "msgBox": $('#message_box'),
            "loader": null,
            "loader_top": $('#call_loader'),
            "loader_bottom": null,
            "parent": $(this).parent(),
            "url": 'sbd/calls/',
            "sort": [],
            "additional_data": {},
            "imei": $('#imei').val(),
            "row_count": $('#call_rows'),
            "rows": $('#call_rows').val(), //rows per fetch
            "total": 0, //total records
            "records": 0, //records displayed
            "type": null,
            "tab": null,
            "extender": null,
            "debug": true,
            'active': false,
            "requestID": 0,
            "initialized": false,
            "even_row": false,
            "empty": true
        }
        this.columns = [];
        this.options = $.extend(this.defaults, options);
        //this.options.start_date = $('#'+ this.options.type + '_start');
        //this.options.end_date = $('#'+ this.options.type + '_end');
        this.options.title = $('#'+ this.options.type + '_title');
        this.options.call_filter = $('#'+ this.options.type + '_filter');

        this.setActive = function(){
            ins.options.active = true;
            var type = ins.options.type;
            //ins.options.start_date.val($('#start_date').val());
            //ins.options.end_date.val($('#end_date').val());
            ins.options.title.html(ins.getTime());
        }
        
        this.setInActive = function(){
            ins.options.active = false;
        }
        this.getTime = function(){
            var startTime = $('#start_date').val() + ' ' + $('#start_hour').val() + ':' + $('#start_minute').val();
            var endTime = $('#end_date').val() + ' ' + $('#end_hour').val() + ':' + $('#end_minute').val();
            return startTime + ' - ' + endTime;
        }
        this.submitForm = function(data){
            this.hideMsg();

            //console.log('SUBMIT FORM: ' + ins.options.tab)
            var filter = ins.options.call_filter.val();
            //var startDate = ins.options.start_date.val();
            //var endDate = ins.options.end_date.val();

            //console.log($('tbody', $(ins.options.id)).html());
            var tbl = $('tbody', $(ins.options.id)).html();
            //console.log(filter == $('#call_filter').val());
            //console.log((ins.options.title.html() == ins.getTime()));
            //console.log(ins.options.empty == false);
            if(filter == $('#call_filter').val() && (ins.options.title.html() == ins.getTime()) && ins.options.empty == false){
                var msg = 'The dates requested are already displayed for this Call Type.';
                this.buildMsg('alert', msg);
            }else{
                ins.options.title.html(ins.getTime());
                ins.options.call_filter.val($('#call_filter').val());
                //ins.options.start_date.val($('#start_date').val());
                //ins.options.end_date.val($('#end_date').val());
                //ins.options.start_hour.val($('#start_hour').val());
                //ins.options.end_hour.val($('#end_hour').val());
                //ins.options.start_minute.val($('#start_minute').val());
                //ins.options.end_minute.val($('#end_minute').val());
                ins.options.empty = false;
                this.requestData(true);
            }
        }
        this.showLoader = function(){
            ins.options.loader.css({
                'height': $(ins.options.id).height(),
                'width': $(ins.options.id).width()
            });
            ins.options.loader_top.removeClass('invisible');
            ins.options.loader.removeClass('invisible');
        }
        this.hideLoader = function(){
            ins.options.loader_top.addClass('invisible');
            ins.options.loader.addClass('invisible');
        }
        this.buildMsg = function(type, message){
            var output = '<div class="' + type + ' message">' + message + '</div>';
            this.displayMsg(output);
        }
        this.displayMsg = function(html){
            ins.options.msgBox.html(html);
            ins.options.msgBox.slideDown();
        }
        this.hideMsg = function(){
            ins.options.msgBox.html('');
        }
        this.clickManager = function(event, self){
            for(var i=0; i < this.columns.length; i++){
                var col = this.columns[i];
                //_TEDebugger(col.ele.text() + ' ' + i + " " + col.dir);
            }
            ins.requestData(true);
        }
        this.requestData = function(newData){
            data = {};
            data['start_date'] =  $('#start_date').val();
            data['end_date'] =  $('#end_date').val();
            data['start_hour'] =  $('#start_hour').val();
            data['end_hour'] =  $('#end_hour').val();
            data['start_minute'] =  $('#start_minute').val();
            data['end_minute'] =  $('#end_minute').val();
            data['filter'] =  this.options.call_filter.val() || '';
            data['sub'] = $('#account_no').val();
            if(newData){
                this.options.requestID = 0;
                this.options.records = 0;
                this.options.even_row = false;
            }else{
                this.options.requestID++;
            }
            data['requestID'] = this.options.requestID;
            data['rows'] = this.options.rows;
            data['from'] = this.options.records;
            data['imei'] = this.options.imei;
            data['sort'] = 0;
            data['type'] = this.options.type;
            var cols = this.columns;
            var col = null;
            for(var i in cols){
                col = cols[i];
                if(col.dir){
                    data['sort']++;
                    data['sort_' +  data['sort']] = col.index + ',' + col.dir;
                    
                }
            }
            if(this.options.additional_data){
                var ad = this.options.additional_data;
                for(var i in ad){
                    data[i] = ad[i];
                }
            }
            _TEDebugger('click: ');
            _TEDebugger(data);
            this.showLoader();

            var a = new AjaxRequest({
                'url': this.options.url,
                'data': data,
                'success': ins.processData
            });
            //$.post(this.options.url, data, this.processData, 'json');
            
        }
        this.processData = function(data){
            ins.hideLoader();
            ins.options.total = data.total;
            var len = data.rows.length;
            ins.options.records += len;
            var html = '';
            if(len > 0){
               var row = null;
               for(var i=0; i < len; i++){
                   row = data.rows[i];
                   var r = [];
                   for(var j=0; j < row.length; j++){
                       r.push(row[j]);
                   }
                   css = ins.options.even_row? 'even' : '';
                   html += '<tr class="' + css + '"><td>' + r.join('</td><td>') + '</td></tr>';
                   ins.options.even_row = !ins.options.even_row;
               }
                if(data.requestID == 0){
                    $('tbody', $(ins.options.id)).html($(html));
                }else{
                    $('tbody', $(ins.options.id)).append($(html));
                }

                if(ins.options.records < ins.options.total && ins.options.total > 0){
                    ins.options.extender.removeClass('invisible');
                }else{
                    ins.options.extender.addClass('invisible');
                }
            }else{
                ins.buildMsg('alert','No data was found for the requested dates and filters.');
                html += '<tr><td align="center" colspan="' + ins.columns.length + '">No Data Found</td></tr>';
                $('tbody', $(ins.options.id)).html($(html));
                ins.options.extender.addClass('invisible');
            }
            ins.update_infobars();
            //console.log(html); 
            

        }
        this.update_infobars = function(){
            var top = this.options.infobar_top;
            var bottom = this.options.infobar_bottom;
            var html = "Displaying: <strong>" + this.options.records + "</strong> of <strong>";
            html += this.options.total + "</strong>";
            top.html(html);            
            bottom.html(html);
        }
        this.moveScroll = function($dir){
            //var scroll = '+=200px';
            if($dir == 'left'){
                ins.options.parent.scrollTo(0,{'easing': 'linear'});
                //scroll = '-=200px';
            }else{
                ins.options.parent.scrollTo('max',{'easing': 'linear'});
            }
            //ins.options.parent.scrollTo(max)
            //ins.options.parent.scrollTo(scroll, ins.options.parent.width());
        }
        var ins = this;
        return this.each(function(){
            //Setup Columns
            $('th', $(this)).each(function(index){
                var obj = new TEColumn;
                obj.load(index, this, ins);
                ins.columns.push(obj);
            });
            if(!ins.options.initialized){
                var infobar_top = $('<div id="' + ins.options.type + '_tbl_extender_infobar_top" class="tbl_extender_infobar left"></div>');
                var infobar_bottom = $('<div id="' + ins.options.type + '_tbl_extender_infobar_bottom" class="tbl_extender_infobar left"></div>');
                
                ins.options.infobar_top = infobar_top;
                var infobar_top_scroll = $('<div id="' + ins.options.type + '_tbl_extender_infobar_top_scroll" class="right tbl_extender_infobar_top_scroll"> scroll </div>');
                var infobar_scroll_left = $('<a href="#content"><<</a>');
                var infobar_scroll_right = $('<a href="#content">>></a>');
                ins.options.infobar_scroll_left = infobar_scroll_left;
                ins.options.infobar_scroll_right = infobar_scroll_right;
                
                ins.options.infobar_top_scroll = infobar_top_scroll;
                ins.options.infobar_top_scroll.prepend(infobar_scroll_left);
                ins.options.infobar_top_scroll.append(infobar_scroll_right);
                ins.options.infobar_bottom = infobar_bottom;
                ins.options.parent.before(infobar_top);
                ins.options.parent.before(infobar_top_scroll);
                ins.options.parent.after(infobar_bottom);
                var extender = $('<div id="' + ins.options.type + '_tbl_extender" class="tbl_extender invisible">Load More Rows</div>');
                ins.options.extender = extender;
                ins.options.parent.after(extender);

                var loader = $('<div id="' + ins.options.type + '_loader" class="tbl_extender_loader invisible"></div>');
                var initialRow = $('<tr><td align="center" colspan="' + ins.columns.length + '">Use the form above to find Records.</td></tr>');
                $('tbody', $(ins.options.id)).html(initialRow);
                ins.options.loader = loader;
                $(ins).after(loader);
                ins.options.row_count.bind('change', function(event){
                    ins.options.rows = $(this).val();
                });

                ins.options.extender.bind('click', function(event){
                    ins.requestData(false);
                });
                ins.options.infobar_scroll_left.bind('click', function(event){
                   event.stopPropagation();
                   ins.moveScroll('left');
                });
                ins.options.infobar_scroll_right.bind('click', function(event){
                   event.stopPropagation();
                   ins.moveScroll('right');
                });
                ins.options.initialized = true;
            }
        });
    }
})(jQuery);
